package com.Q04;

import com.common.TreeNode;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;

/**
 * @version v1.0.0
 * 创建时间：2022/7/6 13:57
 */
public class Q04_09 {
    LinkedList<List<Integer>> res = new LinkedList<>();
    public List<List<Integer>> BSTSequences(TreeNode root) {
        if(root==null) {
            res.add(new LinkedList<>());
            return res;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        recur(new LinkedList<>(),queue);
        return res;
    }

    private void recur(LinkedList<Integer> path,LinkedList<TreeNode> queue){
        if (queue.isEmpty()){
            res.add(new LinkedList<>(path));
            return ;
        }
        LinkedList<TreeNode> copy = new LinkedList<>(queue);
        for (int i = 0; i < queue.size(); i++) {
            TreeNode t = queue.get(i);
            path.add(t.val);
            queue.remove(i);
            if (t.left!=null){
                queue.add(t.left);
            }
            if (t.right!=null) {
                queue.add(t.right);
            }
            recur(path,queue);
            queue = new LinkedList<>(copy);// 直接赋值会导致修改queue影响copy
            path.removeLast();
        }
    }

    public static void main(String[] args) {
        List<List<Integer>> lists = new Q04_09().BSTSequences(TreeNode.buildTree(new Integer[]{5,2,8,1,3,6,null,null,null,null,4,null,7}));
        lists.forEach(x -> {
            x.forEach(System.out::print);
            System.out.println();
        });
    }
}
